<template>



	<div class="system-systemUserdmin-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="1400px">

			<el-card shadow="hover">
				<el-form :model="state.ruleForm" ref="datainterfaceDialogFormRef" :rules="rules" size="default"
					label-width="120px">
					<el-row :gutter="35">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="角色编码" prop="roleCode">
								<el-input v-model="state.ruleForm.roleCode" placeholder="请输入角色编码" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="角色名称" prop="roleName">
								<el-input v-model="state.ruleForm.roleName" placeholder="请输入角色名称" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="状态" prop="status">
								<el-select clearable v-model="state.ruleForm.status">
									<el-option v-for="item in state.statusList" :key="item.dicItemValue"
										:label="item.dicItemName" :value="parseInt(item.dicItemValue)" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</el-card>

			<el-card style="margin-top: 20px;" shadow="hover">
				<el-tabs v-model="state.activeTabName" type="border-card">
					<el-tab-pane lazy name="roleOperatorTab" label="操作权限配置">
						<el-row>
							<el-col :span="11" class="mb20">
								<el-card shadow="hover">
									<el-form>
										<el-row :gutter="10">
											<el-col :span="20">
												<el-form-item label="关键字:">
													<el-input clearable size="default" v-model="state.operator.keyWord"
														placeholder="关键字模糊查询，可按列表字段模糊查询"></el-input>
												</el-form-item>
											</el-col>
											<el-col :span="4">
												<el-button style="margin-top: 4px;" type="primary" size="default"
													@click="permissionResouceListTable_query">过滤</el-button>
											</el-col>
										</el-row>
									</el-form>
								</el-card>
								<el-table size="default" @selection-change="handleSelectionChange1" :max-height="450"
									:data="state.operator.leftList" style="width: 100%">
									<el-table-column type="selection" width="45"></el-table-column>
									<el-table-column label="belongMicroservice"
										prop="belongMicroservice"></el-table-column>
									<el-table-column label="resourcePath" prop="resourcePath"></el-table-column>
									<el-table-column label="resourceName" prop="resourceName"></el-table-column>
								</el-table>

								<!-- <el-pagination v-if="state.dialog.type == 'edit'" @size-change="onHandleSizeChange1"
									@current-change="onHandleCurrentChange1" class="mt15" :pager-count="5"
									:page-sizes="[40, 80, 100]" v-model:current-page="state.operator.page" background
									v-model:page-size="state.operator.limit"
									layout="total, sizes, prev, pager, next, jumper" :total="state.operator.total">
								</el-pagination> -->
							</el-col>
							<el-col :span="2" class="mb20">
								<div class="alig_container">
									<div>
										<el-button @click="leftToRight1" type="primary" size="default"> {{ '>'}}
										</el-button>
									</div>
									<div>
										<el-button @click="rightToLeft1" type="primary" size="default"> {{ '<'}}
												</el-button>
									</div>
								</div>
							</el-col>
							<el-col :span="11" class="mb20">
								<el-table size="default" @selection-change="handleSelectionChange2" :max-height="560"
									:data="state.operator.rightList" style="width: 100%">
									<el-table-column label="已有操作权限">
										<el-table-column type="selection" width="45"></el-table-column>
										<el-table-column label="belongMicroservice"
											prop="belongMicroservice"></el-table-column>
										<el-table-column label="resourcePath" prop="resourcePath"></el-table-column>
										<el-table-column label="resourceName" prop="resourceName"></el-table-column>
									</el-table-column>
								</el-table>
							</el-col>
						</el-row>
					</el-tab-pane>
					<el-tab-pane lazy name="roleDatainterfaceTab" label="数据接口权限配置"><el-row>
							<el-col :span="11" class="mb20">
								<el-card shadow="hover">
									<el-form>
										<el-row :gutter="10">
											<el-col :span="20">
												<el-form-item label="关键字:">
													<el-input clearable size="default"
														v-model="state.dataInterface.keyWord"
														placeholder="关键字模糊查询，可按列表字段模糊查询"></el-input>
												</el-form-item>
											</el-col>
											<el-col :span="4">
												<el-button style="margin-top: 4px;" type="primary" size="default"
													@click="frameRoleDataInterfaceAllListTable_query">过滤</el-button>
											</el-col>
										</el-row>
									</el-form>
								</el-card>
								<el-table size="default" @selection-change="handleSelectionChange3" :max-height="450"
									:data="state.dataInterface.leftList" style="width: 100%">
									<el-table-column type="selection" width="45"></el-table-column>
									<el-table-column label="microServiceName" prop="microServiceName"></el-table-column>
									<el-table-column label="interfaceName" prop="interfaceName"></el-table-column>
								</el-table>
								<!-- <el-pagination v-if="state.dialog.type == 'edit'" @size-change="onHandleSizeChange2"
									@current-change="onHandleCurrentChange2" class="mt15" :pager-count="5"
									:page-sizes="[40, 80, 100]" v-model:current-page="state.dataInterface.page"
									background v-model:page-size="state.dataInterface.limit"
									layout="total, sizes, prev, pager, next, jumper" :total="state.dataInterface.total">
								</el-pagination> -->
							</el-col>
							<el-col :span="2" class="mb20">
								<div class="alig_container">
									<div>
										<el-button type="primary" size="default" @click="leftToRight2"> {{ '>'}}
										</el-button>
									</div>
									<div>
										<el-button type="primary" size="default" @click="rightToLeft2"> {{ '<'}}
												</el-button>
									</div>
								</div>
							</el-col>
							<el-col :span="11" class="mb20">
								<el-table size="default" @selection-change="handleSelectionChange4"
									:data="state.dataInterface.rightList" style="width: 100%">
									<el-table-column label="已有数据接口权限">
										<el-table-column type="selection" width="45"></el-table-column>
										<el-table-column label="microServiceName"
											prop="microServiceName"></el-table-column>
										<el-table-column label="interfaceName" prop="interfaceName"></el-table-column>
									</el-table-column>
								</el-table>
							</el-col>
						</el-row></el-tab-pane>
				</el-tabs>
			</el-card>


			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>

	</div>
</template>

<script setup lang="ts" name="systemDicDialog">
import { ElMessage } from 'element-plus';
import { reactive, ref, watch } from 'vue';




// 导入接口
import { useSysApi } from "../../../api/sys";


const datainterfaceDialogFormRef = ref();


// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);


const rules = {
	roleCode: [
		{ required: true, message: "请输入角色编码", trigger: "blur" },
		{ min: 4, max: 50, message: "长度在 4 到 50 个字符", trigger: "blur" }
	],
	roleName: [
		{ required: true, message: "请输入角色名称", trigger: "blur" },
		{ min: 4, max: 50, message: "长度在 4 到 50 个字符", trigger: "blur" }
	],
	status: [
		{ required: true, message: "请选择状态", trigger: "blur" }
	],
}


const state = reactive({
	roleId: "",
	activeTabName: "roleOperatorTab", // 当前选项卡
	ruleForm: {
		roleCode: "",
		roleName: "",
		status: ""
	} as any,
	statusList: [] as any,

	operator: {
		keyWord: "",
		page: 1,
		limit: 40,
		total: 0,
		multipleSelection1: [] as any,
		multipleSelection2: [] as any,
		leftList: [] as any,
		rightList: [] as any
	},
	dataInterface: {
		keyWord: "",
		page: 1,
		limit: 40,
		total: 0,
		multipleSelection1: [] as any,
		multipleSelection2: [] as any,
		leftList: [] as any,
		rightList: [] as any
	},



	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});


const initData = async () => {
	// 获取操作权限公共
	await permissionResouceListTable_query();
	await frameRoleDataInterfaceAllListTable_query();
}


const initRoleData = async () => {
	// 获取操作权限公共

	let tempList = [] as any;
	tempList = await useSysApi().queryDynamicSqlList("6a58842f2dab21009867e5d7782985ec", {
		params: { roleId: state.roleId },
		sorts: "fr.belong_microservice, fr.resource_path, fr.resource_name, frr.resource_id, frr.role_resource_id"
	});
	state.operator.rightList = tempList;


	tempList = await useSysApi().queryDynamicSqlList("7d458ef7f373239fd213efa213a30091", {
		params: { roleId: state.roleId },
		sorts: "belong_microservice,data_interface_name"
	});

	let temp = [] as any;
	tempList.forEach((element: any) => {
		temp.push({
			md5: element.dataInterfaceId,
			microServiceName: element.belongMicroservice,
			interfaceName: element.dataInterfaceName
		})
	});
	state.dataInterface.rightList = temp;
}





const permissionResouceListTable_query = async () => {
	let vo = {} as any;
	if (state.operator.keyWord) vo["keyWord"] = state.operator.keyWord;
	// 获取操作权限公共
	let tempList = await useSysApi().queryOperateLegalPower("ff4211d5f54026dc74e8de937a18b790", state.operator.page, state.operator.limit, {
		params: vo,
		sorts: "belong_microservice,resource_path,resource_name"
	});
	state.operator.total = tempList.total;
	// 根据用户的权限去重
	let remp = tempList.list.filter((x: any) => {
		let rs = state.operator.rightList.some((b: any) => {
			return b.resourceId == x.resourceId;
		})
		return !rs;
	})
	state.operator.leftList = remp;
}


const handleSelectionChange1 = (val: any) => {
	state.operator.multipleSelection1 = val;
}
const handleSelectionChange2 = (val: any) => {
	state.operator.multipleSelection2 = val;
}



const handleSelectionChange3 = (val: any) => {
	state.dataInterface.multipleSelection1 = val;
}
const handleSelectionChange4 = (val: any) => {
	state.dataInterface.multipleSelection2 = val;
}





const leftToRight2 = () => {
	if (state.dataInterface.multipleSelection1.length <= 0) return;
	const listTemp = [] as any;
	state.dataInterface.multipleSelection1.map((x: any) => {
		let indexR = state.dataInterface.rightList.findIndex((y: any) => y.md5 == x.md5);
		if (indexR < 0) {
			listTemp.push(x);
		}
	});

	state.dataInterface.rightList.push(...listTemp);


	// if (state.dialog.type != 'edit') {
	// 如果是新增加需要把原数据去除勾选

	let remp = state.dataInterface.leftList.filter((x: any) => {
		let rs = state.dataInterface.multipleSelection1.some((b: any) => {
			return b.md5 == x.md5;
		})
		return !rs;
	})
	state.dataInterface.leftList = remp;

	// }
}


const leftToRight1 = () => {
	if (state.operator.multipleSelection1.length <= 0) return;
	const listTemp = [] as any;
	state.operator.multipleSelection1.map((x: any) => {
		let indexR = state.operator.rightList.findIndex((y: any) => y.resourceId == x.resourceId);
		if (indexR < 0) {
			listTemp.push(x);
		}
	});

	state.operator.rightList.push(...listTemp);


	// if (state.dialog.type != 'edit') {
	// 如果是新增加需要把原数据去除勾选

	let remp = state.operator.leftList.filter((x: any) => {
		let rs = state.operator.multipleSelection1.some((b: any) => {
			return b.resourceId == x.resourceId;
		})
		return !rs;
	})
	state.operator.leftList = remp;

	// }
}

const rightToLeft1 = () => {
	if (state.operator.multipleSelection2.length <= 0) return;
	const listTemp = [] as any;
	state.operator.multipleSelection2.map((x: any) => {
		let indexR = state.operator.leftList.findIndex((y: any) => y.resourceId == x.resourceId);
		if (indexR < 0) {
			listTemp.push(x);
		}
	});

	state.operator.leftList.push(...listTemp);


	// if (state.dialog.type != 'edit') {
	// 如果是新增加需要把原数据去除勾选

	let remp = state.operator.rightList.filter((x: any) => {
		let rs = state.operator.multipleSelection2.some((b: any) => {
			return b.resourceId == x.resourceId;
		})
		return !rs;
	})
	state.operator.rightList = remp;

	// }
}



const rightToLeft2 = () => {
	if (state.dataInterface.multipleSelection2.length <= 0) return;
	const listTemp = [] as any;
	state.dataInterface.multipleSelection2.map((x: any) => {
		let indexR = state.dataInterface.leftList.findIndex((y: any) => y.md5 == x.md5);
		if (indexR < 0) {
			listTemp.push(x);
		}
	});

	state.dataInterface.leftList.push(...listTemp);


	// if (state.dialog.type != 'edit') {
	// 如果是新增加需要把原数据去除勾选

	let remp = state.dataInterface.rightList.filter((x: any) => {
		let rs = state.dataInterface.multipleSelection2.some((b: any) => {
			return b.md5 == x.md5;
		})
		return !rs;
	})
	state.dataInterface.rightList = remp;

	// }
}









// 分页改变
const onHandleSizeChange1 = (val: number) => {
	state.operator.limit = val;
	permissionResouceListTable_query();
};
// 分页改变
const onHandleCurrentChange1 = (val: number) => {
	state.operator.page = val;
	permissionResouceListTable_query();
};



const frameRoleDataInterfaceAllListTable_query = async () => {
	let vo = {
		params: [
			{
				name: "authMethod",
				relationalOperator: "AND",
				operator: "IS",
				value: "BYUSERPERMISSION"
			},
			{
				name: "microServiceName",
				relationalOperator: "OR",
				operator: "REGEX",
				value: state.dataInterface.keyWord || ""
			},
			{
				name: "interfaceName",
				relationalOperator: "OR",
				operator: "REGEX",
				value: state.dataInterface.keyWord || ""
			}
		],
		orders: [
			{
				direction: "ASC",
				property: "microServiceName"
			},
			{
				direction: "ASC",
				property: "interfaceName"
			}
		],
		fields: {
			microServiceName: true,
			interfaceName: true,
			authMethod: true,
			md5: true
		}
	}


	// 获取操作权限公共
	let tempList = await useSysApi().pagedQueryDataInterface(state.dataInterface.page, state.dataInterface.limit, vo);
	state.dataInterface.total = tempList.total;
	// state.dataInterface.leftList = tempList.list;

	// 根据用户的权限去重
	let remp = tempList.list.filter((x: any) => {
		let rs = state.dataInterface.rightList.some((b: any) => {
			return b.md5 == x.md5;
		})
		return !rs;
	})
	state.dataInterface.leftList = remp;

}



// 分页改变
const onHandleSizeChange2 = (val: number) => {
	state.dataInterface.limit = val;
	frameRoleDataInterfaceAllListTable_query();
};
// 分页改变
const onHandleCurrentChange2 = (val: number) => {
	state.dataInterface.page = val;
	frameRoleDataInterfaceAllListTable_query();
};







// 打开弹窗
const openDialog = async (type: string, row?: any) => {

	state.dialog.type = type;
	// 不管是新开还是编辑选项卡优选选中第一个
	state.activeTabName = 'roleOperatorTab';


	// if (state.dialog.type != 'edit') {
	// 	state.operator.limit = 1000
	// 	state.dataInterface.limit = 1000
	// } else {
	// 	state.operator.limit = 40
	// 	state.dataInterface.limit = 40
	// }


	state.operator.limit = 1000
	state.dataInterface.limit = 1000

	state.operator.keyWord = "";
	state.dataInterface.keyWord = "";



	if (type === 'edit') {
		state.dialog.title = '修改角色信息';
		state.dialog.submitTxt = '修 改';
		state.roleId = row.roleId;

		state.ruleForm = {
			roleCode: row.roleCode,
			roleName: row.roleName,
			status: row.status
		}

		await initRoleData();

	} else {
		state.roleId = "";
		state.ruleForm = {
			roleCode: "",
			roleName: "",
			status: 1
		}
		state.operator.rightList = [];
		state.dataInterface.rightList = [];
		state.dialog.title = '新增角色';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
	}


	// 获取公共数据
	await initData();
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};


// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {



	// 检查顶层表单
	datainterfaceDialogFormRef.value.validate(async (valid: any) => {
		if (valid) {
			//检查参数列表
			let vo = {
				roleCode: state.ruleForm.roleCode,
				roleName: state.ruleForm.roleName,
				status: state.ruleForm.status
			} as any;

			let tempList = [] as any;
			if (state.operator.rightList.length > 0) {
				state.operator.rightList.forEach((element: any) => {
					if (state.roleId) element.roleId = state.roleId;
					tempList.push(element)
				});
			}
			vo["frameRoleResourceList"] = tempList;
			vo["frameRoleResourceUpdateFlag"] = true;

			let tempList1 = [] as any;
			if (state.dataInterface.rightList.length > 0) {
				state.dataInterface.rightList.forEach((element: any) => {
					let vo = {
						belongMicroservice: element.microServiceName,
						dataInterfaceId: element.md5,
						dataInterfaceName: element.interfaceName
					} as any;
					if (state.roleId) vo.roleId = state.roleId;

					tempList1.push(vo);
				});
			}
			vo["frameRoleDataInterfaceList"] = tempList1;
			vo["frameRoleDataInterfaceUpdateFlag"] = true;

			if (state.roleId) { vo["roleId"] = state.roleId; }

			try {
				await useSysApi().saveOrUpdateFrameRole(vo);
				ElMessage.success("操作成功");
				closeDialog(); // 关闭弹窗
				emit('refresh');
			} catch (error) {
				ElMessage.error("操作失败请稍后再试");
			}


		} else {
			ElMessage.warning("请检查数据的正确性！");
		}
	})
};




const selectDicItemsByDicCode = async () => {
	state.statusList = await useSysApi().selectDicItemsByDicCode("commStatus", "General");
}


watch(
	() => state.dialog.isShowDialog,
	(newValue) => {
		if (newValue == true) {
			selectDicItemsByDicCode();
		}
	}, { immediate: true }
);


// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss">
.el-select {
	width: 100% !important;
}



.system-systemUserdmin-dialog-container {
	.bar_tools {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.el-table__expanded-cell {
		padding: 20px;
	}


	.alig_container {
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;

		&>div {
			margin: 15px 0px;
			display: flex;
			justify-content: center;
		}
	}
}
</style>